import { defineStore } from 'pinia'
import { 
  createComment, updateComment, deleteComment, 
  deleteCommentsByNoteId, getCommentById, 
  getCommentsTreeByNoteId, getCommentsByUserId, 
  getRepliesByParentId, getCommentCountByNoteId, 
  getCommentCountByUserId 
} from '@/api/comments'

export const useCommentStore = defineStore('comments', {
  state: () => ({
    comments: [], // 存储树形结构的评论列表
    currentComment: null, // 当前选中的评论
    isLoading: false,
    error: null,
    commentCounts: {} // 存储笔记ID到评论数的映射
  }),
  
  actions: {
    // 创建新评论
    async createComment(commentData) {
      this.isLoading = true
      this.error = null
      try {
        // 确保 parentId 为 null 或 0 时设置为 null
        if (commentData.parentId === null || commentData.parentId === 0) {
          commentData.parentId = null
        }
        
        const response = await createComment(commentData)
        const newComment = response.data
        
        // 如果是顶级评论，直接添加到列表
        if (newComment.parentId === null) {
          this.comments.push(newComment)
        } 
        // 如果是回复，找到父评论并添加到其replies中
        else {
          const parentComment = this.findCommentById(newComment.parentId)
          if (parentComment) {
            if (!parentComment.replies) {
              parentComment.replies = []
            }
            parentComment.replies.push(newComment)
          }
        }
        
        // 更新评论计数
        if (newComment.noteId) {
          this.commentCounts[newComment.noteId] = 
            (this.commentCounts[newComment.noteId] || 0) + 1
        }
        
        return newComment
      } catch (error) {
        this.error = error.response?.data?.message || '创建评论失败'
        throw error
      } finally {
        this.isLoading = false
      }
    },
    
    // 更新评论
    async updateComment(id, commentData) {
      this.isLoading = true
      this.error = null
      try {
        const response = await updateComment(id, commentData)
        const updatedComment = response.data
        
        // 更新store中的评论
        const commentToUpdate = this.findCommentById(id)
        if (commentToUpdate) {
          Object.assign(commentToUpdate, updatedComment)
        }
        
        // 如果当前正在查看的评论是更新的评论，则更新currentComment
        if (this.currentComment && this.currentComment.id === id) {
          this.currentComment = updatedComment
        }
        
        return updatedComment
      } catch (error) {
        this.error = error.response?.data?.message || '更新评论失败'
        throw error
      } finally {
        this.isLoading = false
      }
    },
    
    // 删除评论
    async deleteComment(id) {
      this.isLoading = true
      this.error = null
      try {
        await deleteComment(id)
        
        // 从store中删除评论
        this.removeCommentById(id)
        
        // 如果删除的是当前选中的评论，则清空currentComment
        if (this.currentComment && this.currentComment.id === id) {
          this.currentComment = null
        }
        
        return true
      } catch (error) {
        this.error = error.response?.data?.message || '删除评论失败'
        throw error
      } finally {
        this.isLoading = false
      }
    },
    
    // 删除笔记的所有评论
    async deleteCommentsByNoteId(noteId) {
      this.isLoading = true
      this.error = null
      try {
        await deleteCommentsByNoteId(noteId)
        
        // 从store中删除该笔记的所有评论
        this.comments = this.comments.filter(comment => comment.noteId !== noteId)
        
        // 重置评论计数
        this.commentCounts[noteId] = 0
        
        return true
      } catch (error) {
        this.error = error.response?.data?.message || '删除笔记评论失败'
        throw error
      } finally {
        this.isLoading = false
      }
    },
    
    // 获取单个评论
    async fetchCommentById(id) {
      this.isLoading = true
      this.error = null
      try {
        const response = await getCommentById(id)
        this.currentComment = response.data
        return this.currentComment
      } catch (error) {
        this.error = error.response?.data?.message || '获取评论失败'
        throw error
      } finally {
        this.isLoading = false
      }
    },
    
    // 获取笔记的评论树
    async fetchCommentsTreeByNoteId(noteId) {
      this.isLoading = true
      this.error = null
      try {
        const response = await getCommentsTreeByNoteId(noteId)
        // 确保返回的是数组类型
        this.comments = Array.isArray(response.data) ? response.data : []
        return this.comments
      } catch (error) {
        this.error = error.response?.data?.message || '获取笔记评论失败'
        this.comments = [] // 出错时设置为空数组
        throw error
      } finally {
        this.isLoading = false
      }
    },
    
    // 获取用户的所有评论
    async fetchCommentsByUserId(userId) {
      this.isLoading = true
      this.error = null
      try {
        const response = await getCommentsByUserId(userId)
        return response.data
      } catch (error) {
        this.error = error.response?.data?.message || '获取用户评论失败'
        throw error
      } finally {
        this.isLoading = false
      }
    },
    
    // 获取评论的回复
    async fetchRepliesByParentId(parentId) {
      this.isLoading = true
      this.error = null
      try {
        const response = await getRepliesByParentId(parentId)
        return response.data
      } catch (error) {
        this.error = error.response?.data?.message || '获取回复失败'
        throw error
      } finally {
        this.isLoading = false
      }
    },
    
    // 获取笔记的评论总数
    async fetchCommentCountByNoteId(noteId) {
      this.isLoading = true
      this.error = null
      try {
        const response = await getCommentCountByNoteId(noteId)
        const count = response.data
        this.commentCounts[noteId] = count
        return count
      } catch (error) {
        this.error = error.response?.data?.message || '获取评论数失败'
        throw error
      } finally {
        this.isLoading = false
      }
    },
    
    // 获取用户的评论总数
    async fetchCommentCountByUserId(userId) {
      this.isLoading = true
      this.error = null
      try {
        const response = await getCommentCountByUserId(userId)
        return response.data
      } catch (error) {
        this.error = error.response?.data?.message || '获取用户评论数失败'
        throw error
      } finally {
        this.isLoading = false
      }
    },
    
    // 更新评论数
    updateCommentCount(noteId, count) {
      this.commentCounts[noteId] = count
    },
    
    // 辅助函数：计算评论树中的评论总数（包括所有回复）
    countCommentsInTree(comment) {
      let count = 1 // 包括自身
      if (comment.replies && comment.replies.length > 0) {
        comment.replies.forEach(reply => {
          count += this.countCommentsInTree(reply)
        })
      }
      return count
    },
    
    // 辅助函数：在评论树中查找评论
    findCommentById(id, comments = this.comments) {
      for (const comment of comments) {
        if (comment.id === id) {
          return comment
        }
        if (comment.replies && comment.replies.length > 0) {
          const found = this.findCommentById(id, comment.replies)
          if (found) return found
        }
      }
      return null
    },
    
    // 辅助函数：从评论树中删除评论
    removeCommentById(id, comments = this.comments) {
      for (let i = 0; i < comments.length; i++) {
        const comment = comments[i]
        if (comment.id === id) {
          // 更新评论计数
          if (comment.noteId) {
            this.commentCounts[comment.noteId] = 
              Math.max(0, (this.commentCounts[comment.noteId] || 0) - this.countCommentsInTree(comment))
          }
          
          // 删除评论
          comments.splice(i, 1)
          return true
        }
        if (comment.replies && comment.replies.length > 0) {
          const removed = this.removeCommentById(id, comment.replies)
          if (removed) return true
        }
      }
      return false
    }
  },
  
  getters: {
    // 获取指定笔记的评论数
    getCommentCountByNoteId: (state) => (noteId) => {
      return state.commentCounts[noteId] || 0
    }
  }
})